﻿using SW.EF.Core;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace SW.EF.DAL
{
    public static class DbContextHelper
    {
        private const string KEY_DBCONTEXT = "dbcontext";

        public static void InitDbContext(DbContext dbContext)
        {
            HttpContext.Current.Items.Add(KEY_DBCONTEXT, dbContext);
        }

        public static T GetDbContext<T>()
        {
            if (HttpContext.Current == null || !HttpContext.Current.Items.Contains(KEY_DBCONTEXT))
            {
                return Engine.IocProvider.Resolve<T>();
            }
            else
            {
                return (T)HttpContext.Current.Items[KEY_DBCONTEXT];
            }            
        }

        public static void RemoveDbContext()
        {
            var dbContext = HttpContext.Current.Items[KEY_DBCONTEXT];
            if (dbContext != null)
                HttpContext.Current.Items.Remove(KEY_DBCONTEXT);
        }
    }
}
